#encoding:utf-8
from django.db import models
from collections import defaultdict
#import sys
#reload(sys)
#sys.setdefaultencoding("utf-8")


class ArticleManager(models.Manager):
    def archive(self):
        date_list = Article.objects.datetimes('create_time', 'month', order='DESC')
        date_dict = defaultdict(list)
        for d in date_list:
            date_dict[d.year].append(d.month)
        return sorted(date_dict.items(), reverse=True)


class Article(models.Model):
    objects = ArticleManager()
    title = models.CharField('标题', max_length=100)
    content = models.TextField('正文')
    create_time = models.DateTimeField('创建时间', auto_now_add=True)
    last_modified_time = models.DateTimeField('修改时间', auto_now=True)
    abstract = models.CharField('摘要', max_length=250, blank=True, null=True,
                                help_text="可选，如果为空摘取正文的前54个字符")
    category = models.ForeignKey('Category', verbose_name='分类',
                                 null=True, default='其他',
                                 on_delete=models.SET_NULL)
    tag = models.ManyToManyField('Tag', verbose_name='标签集合', blank=True)

    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ['-create_time']

    def save(self, *args, **kwargs):
        if self.abstract == '':
            self.abstract = self.content[:200] or self.content
        super(self.__class__, self).save(*args, **kwargs)


class Category(models.Model):
    name = models.CharField('类名', max_length=20)
    create_time = models.DateTimeField('创建时间', auto_now_add=True)
    last_modified = models.DateTimeField('x修改时间', auto_now=True)

    def __unicode__(self):
        return self.name


class BlogComment(models.Model):
    user_name = models.CharField('评论者名字', max_length=100)
    user_email = models.EmailField('评论者邮件', max_length=255)
    body = models.TextField('评论内容')
    created_time = models.DateTimeField('评论发表时间', auto_now_add=True)
    article = models.ForeignKey('Article', verbose_name='评论所属文章', on_delete=models.CASCADE)

    def __unicode__(self):
        return self.body[:20]


class Tag(models.Model):
    name = models.CharField('标签名', max_length=20)
    created_time = models.DateTimeField('创建时间', auto_now_add=True)
    last_modified_time = models.DateTimeField('修改时间', auto_now=True)

    def __unicode__(self):
        return self.name




